from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Request, Form
from redis import Redis
from sqlalchemy.orm import Session
from app import schemas
from app.common import get_redis

from app.utils.resp_util import APIResponse
from app.extensions import dependencies as deps
from app.extensions.dependencies import get_query_token2, parse_encryption_header
from app.dependencies.db import get_db
from app.common import exceptions as excs
from app.common.enums.resp_enum import ErrTypes

from app import services

import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix='/basic', tags=['basic'])

@router.get("/is_ip_in_white_list", response_model=APIResponse[bool])
def is_ip_in_white_list(ip_addr: str, r: Redis=Depends(get_redis)):
    logger.info('>> 查询IP是否在白名单')
    res = services.risk.is_ip_in_white_list(r, ip_addr)
    resp = APIResponse()
    resp.data = res
    return resp

@router.get("/ip_white_list", response_model=APIResponse[list[schemas.IPWhiteListBase]])
def get_ip_white_list(db: Session = Depends(get_db)):
    logger.info('>> 查询IP白名单')
    ip_list = services.risk.get_ip_white_list(db)
    resp = APIResponse()
    resp.data = ip_list
    return resp

@router.get("/refresh_ip_whitelist_cache", response_model=APIResponse[list])
def refresh_ip_whitelist_cache(db: Session = Depends(get_db), r: Redis=Depends(get_redis)):
    logger.info('>> 刷新IP白名单缓存数据')
    ip_list = services.risk.refresh_ip_whitelist_cache(db, r)
    resp = APIResponse()
    resp.data = ip_list
    return resp

@router.get("/sync_ip_white_list_cache", response_model=APIResponse[list])
def sync_ip_white_list_cache(db: Session = Depends(get_db), r: Redis=Depends(get_redis)):
    logger.info('>> 同步IP白名单缓存')
    ip_list = services.refresh_ip_whitelist_cache(db, r)
    resp = APIResponse()
    resp.data = ip_list
    return resp